package cn.javaxc.mvcwork.controller;
import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.controller.web.PagedListInfo;
import cn.javaxc.mvcwork.framework.actions.*;
import cn.javaxc.mvcwork.framework.database.ConnectionElement;
import cn.javaxc.mvcwork.modules.admin.Contact;
import cn.javaxc.mvcwork.modules.file.*;
import cn.javaxc.mvcwork.modules.notifier.*;
import cn.javaxc.mvcwork.modules.site.*;
import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.mvcwork.modules.login.UserBean;
import java.lang.reflect.Constructor;
import java.sql.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipOutputStream;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import cn.javaxc.mvcwork.modules.admin.*;
import cn.javaxc.mvcwork.util.helper.*;
import cn.javaxc.model.base.SQLMap;

public class AppUtils {
	public final static String fs = "/";

  
//  public static Object getActualUserId(TActionContext context) {
//    return (MSecurityUtils.getUserEntity()).getActualUserId();
//  }

//  public static void sendCampaign(Connection db,String campId) throws Exception{
//	sendCampaign(db,StringUtils.parseInt(campId,-1));
//  }
//  public static void sendCampaign(Connection db,int campId) throws Exception{
//	NotificationUtils.sendCampaign(db,new Campaign(db,campId),MVCConfig.getConfig().getPrefs(),true);
//  }

  public static String getModuleFileLibrary(TActionContext context,Object moduleId){
	MVCConfig prefs = (MVCConfig) context.getServletContext().getAttribute("mvc");
    if (prefs != null) {
		return getModuleFileLibrary(prefs,moduleId);
	}
	return null;
  }
  public static String getModuleFileLibrary(MVCConfig config,Object moduleId){
	   String base=getModuleFileLibrary(moduleId);
	   if (base!=null){
			return config.get("FILELIBRARY") + fs + config.get("gatekeeper.database") + fs + base + fs;
	   }
	   return null;
  }
  public static String getModuleFileLibrary(Object moduleId){
	  if(moduleId==null)return null;
	  return moduleId+"";
  }
	public static String getBase(TActionContext context){
		String includePage = RequestHelper.getRequestValue(context.getRequest(),"include")+"";
		if(includePage.lastIndexOf("/")==-1)return includePage;
		String base=includePage.substring(0,includePage.lastIndexOf("/"));
		return base;
	}
	public static String getRealPath(String path){
//		return MVCConstant.JSPCTX.replace("templates","mvc.web")+path;
		return "/WEB-INF/mvc.web"+path;
	}

	public static String getBasePath(String filename){
		if (filename.startsWith("/")){
			filename=filename.substring(0,filename.lastIndexOf("/"))+"/"+filename.substring(filename.lastIndexOf("/")+1);			
		}else{
			filename=filename;
		}
		return filename;
	}
	public static String getRealPath(TActionContext context,String path){
		return context.getRequest().getRealPath(getRealPath(path));
	}
	public static void addFormElements(TActionContext context) {
		String includePage = RequestHelper.getRequestValue(context.getRequest(),"include")+"";
//		context.setAttribute("IncludePage", getRealPath(getBasePath(includePage))+context.getConfig().get("layout.suffix",".jsp"));
		context.setAttribute("IncludePage", includePage+context.getConfig().get("layout.suffix",".jsp"));
	}
	public static void setSourcePage(TActionContext context) {
		if (context.getParameter("ttpsource")!=null){
			context.setAttribute("include","/"+context.getParameter("ttpsource"));
//			File file=new File(getRealPath(context,getBasePath(context.getParameter("ttpsource"))+".jsp"));
//			if (file.exists()){
//				context.setAttribute("include",context.getParameter("ttpsource"));
//			}else{
//				context.setAttribute("include",getBase(context)+"/"+context.getParameter("ttpsource"));
//			}
		}
	}
  
  public static SystemStatus getSystemStatus(TActionContext context) {
    return (SystemStatus)context.getServletContext().getAttribute("SystemStatus");
  }




  
  public static PagedListInfo getPagedListInfo(HttpServletRequest context, String viewName) {
    return getPagedListInfo(context, viewName, true);
  }


  
  public static PagedListInfo getPagedListInfo(HttpServletRequest context, String viewName, boolean setParams) {
    PagedListInfo tmpInfo = (PagedListInfo) context.getSession().getAttribute(viewName);
    if (tmpInfo == null || tmpInfo.getId() == null) {
      tmpInfo = new PagedListInfo();
      tmpInfo.setId(viewName);
      context.getSession().setAttribute(viewName, tmpInfo);
    }
    if (setParams) {
      tmpInfo.setParameters(context);
    }
    return tmpInfo;
  }
  
  public static String getDbNamePath(TActionContext context) {
    MVCConfig prefs = (MVCConfig) context.getServletContext().getAttribute("mvc");
    return (prefs.get("FILELIBRARY") + getDbName(context) + fs);
  }


  
  public static String getDatePath(java.util.Date fileDate) {
    return DateUtils.getDatePath(fileDate);
  }


  
  public static String getDatePath(java.sql.Timestamp fileDate) {
    return DateUtils.getDatePath(fileDate);
  }


  
  public static String getDatePath(String filenameDate) {
    if (filenameDate.length() > 7) {
      return (filenameDate.substring(0, 4) + fs +
          filenameDate.substring(4, 8) + fs);
    } else {
      return null;
    }
  }
   
  public static String getPref(TActionContext context, String param) {
    MVCConfig prefs = (MVCConfig) context.getServletContext().getAttribute("mvc");
    if (prefs != null) {
      return prefs.get(param);
    } else {
      return null;
    }
  }


  public static String getDbName(TActionContext context) {
    ConnectionElement ce = (ConnectionElement) context.getSession().getAttribute(
        "ConnectionElement");
    if (ce != null) {
      return ce.getDbName();
    } else {
      return getPref(context,"gatekeeper.database");
    }
  }
	public static String newPassword(TActionContext context,SQLMap user_email,String newPassword) throws Exception{
		return newPassword;
	}
  public static int sendMail(Map user_email,String subject,String message,String file_item_ids,String replyMails){
	  FileItemList attachments = new FileItemList();
	  attachments.setItemIdRange(file_item_ids);
	  attachments.buildList();
	  FileItemList filelist = new FileItemList();
	  for (FileItem thisItem:(List<FileItem>)attachments){	 
        thisItem.setDirectory(getModuleFileLibrary(MVCConfig.getConfig(),thisItem.getLinkModuleId()));
		if (new File(thisItem.getFullFilePath()).exists()){
			filelist.add(thisItem);
		}
      }
	  int result=-1;
	  for (String reply:replyMails.split("\n")){
		  if (!StringUtils.isNullData(reply)){
			SMTPHelper mail = MVCConfig.getConfig().createSMTPHelper();
			mail.addReplyTo(reply);
			mail.addTo(reply);
			mail.setType("text/html");
			mail.setSubject(subject);
			mail.setBody(message);
			mail.setAttachments(filelist);
			if (user_email!=null){
				result=mail.send(user_email);
			}else{
				result=mail.send();
			}
		  }
	  }
	  return result;
  }
}
